package com.wenson.behavior.iterator;


/**
 * @ClassName: DrivingRecorder
 * @Author: luowangcheng
 * @Date: 2024/6/15 12:40
 * @Description:
 */
public class DrivingRecorder2 implements Iterable<String> {
    private int index = -1; //记录当前位置
    private String[] records = new String[10]; //最多记录10条视频

    public void append(String record) {
        if (index == 9) { //索引重置，从头覆盖
            index = 0;
        } else { //正常覆盖下一条
            index++;
        }
        records[index] = record;
    }

    @Override
    public Iterator<String> iterator() {
        return new Itr();
    }


    private class Itr implements Iterator<String> {
        int cursor = index;
        int loopCount = 0;

        @Override
        public boolean hasNext() {
            return loopCount < 10;
        }

        @Override
        public String next() {
            int i = cursor; //记录即将返回的游标位置
            if (cursor == 0) {
                cursor = 9;
            } else {
                cursor--;
            }
            loopCount++;
            return records[i];
        }
    }
}
